package org.jeecg.common.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.Cleanup;
import lombok.SneakyThrows;

import static cn.hutool.core.text.CharSequenceUtil.isBlank;

/**
 * 文件业务
 *
 * @author zjarlin
 * @since 2023/02/23
 */
public interface FileBusinessUtil {
    static String zipFiles(Collection<String> paths) {
        return zipFiles(null, paths);
    }

    /**
     * 默认paths的文件都在一个文件夹可以省略dirname
     *
     * @param zipFileName zip文件名字
     * @param paths       路径 入参
     * @return {@link String }
     * @author zjarlin
     * @since 2023/02/24
     */
    static String zipFiles(String zipFileName, Collection<String> paths) {
        String s = paths.stream().findAny().orElse(null);
        String dirname = FileUtil.getParent(s, 1);
        return zipFiles(dirname, zipFileName, paths);
    }

    /**
     * 批量压缩zip文件
     *
     * @param dirname
     * @param zipFileName zip文件名字
     * @param paths       路径 入参
     * @return {@link String }
     * @author zjarlin
     * @since 2023/02/24
     */
    static String zipFiles(final String dirname, String zipFileName, Collection<String> paths) {
        //List<File> collect = paths.stream().map(e -> FileUtil.file(e)).collect(Collectors.toList());
        String s = paths.stream().findAny().orElse(null);

        String tmpZipName = "tmp";
        File file = FileUtil.mkdir(dirname + File.separator + tmpZipName);
        String tmpAbsolutePath = file.getAbsolutePath();

        paths.forEach(p -> FileUtil.copy(p, tmpAbsolutePath, true));
        File zip = ZipUtil.zip(tmpAbsolutePath);
        String newName = isBlank(zipFileName)
            ?
            LocalTime.now().format(DateTimeFormatter.ofPattern("HH_mm_ss_SSS_")) + "归档.zip"
            //LocalTime.now().toString()
            : zipFileName + ".zip";
        File rename = FileUtil.rename(zip, newName, true);
        boolean del = FileUtil.del(tmpAbsolutePath);

        return rename.getAbsolutePath();
    }

    /**
     * 入参base64字符串,将其保存到savePath目录下,并返回文件保存的路径
     *
     * @param base64Str       入参
     * @param saveAbsRootPath
     * @return {@link String }
     * @author zjarlin
     * @since 2023/02/10
     */
    @SneakyThrows
    static String base64ToUrlWithSavePhoto(String base64Str, final String saveAbsRootPath) {
        if (StrUtil.isBlank(base64Str)) {
            return "";
        }
        //前缀做处理
        base64Str = base64Str.replaceFirst("data:(.+?);base64,", "");
        // boolean isNotBase64 = !cn.hutool.core.codec.Base64.isBase64(base64Str);

        boolean isNotBase64 = !checkForEncode(base64Str);
        //如果不是base64格式就不转换,还按照原来的返回
        if (isNotBase64) {
            return base64Str;
        }
        // DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss_SSS_");
        DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("HH_mm_ss_SSS_");
        String format = dfDateTime.format(LocalDateTime.now());
        String path = saveAbsRootPath + File.separator + format + RandomUtil.randomString(2) + ".png";
        File touch = FileUtil.touch(path);

        @Cleanup FileOutputStream fileOutputStream = new FileOutputStream(touch);
        byte[] bytes = cn.hutool.core.codec.Base64.decode(base64Str);
        // byte[] bytes = java.util.Base64.getMimeDecoder().decode(base64Str);
        fileOutputStream.write(bytes);

        // BufferedImage read = ImageIO.read(touch);
        // boolean isNotImg = read == null;
        //如果生成的不是图片,还按原字符串返回
        // if (isNotImg) {
        //     boolean del = FileUtil.del(touch);
        //     return base64Str;
        // }

        return path;
    }

    static boolean checkForEncode(String string) {
        string = string.replaceFirst("data:(.+?);base64,", "");

        String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        String base64ImageRegex = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$";

        // "[\\/]?([\\da-zA-Z]+[\\/+]+)*[\\da-zA-Z]+([+=]{1,2}|[\\/])?"
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(string);
        boolean b = m.find();
        return b
            // && isValidImage(string)
            ;
    }

}
